﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System;
using System.Web.Security;
using log4net;
using Code.Models;
using QianBuo.Lottery.Web.Models;
using Code.BLL;
using System.Web;

namespace QianBuo.Lottery.Web.Controllers
{
    [HandleError]
    public class BaseController : Controller
    {
        /// <summary>
        /// 当前登录的用户
        /// </summary>
        protected UserModel LoginUser { get;set; }

        protected Guid LoginUserID { get; set; }

        public HashTable<Guid, UserModel> OnLineUsers { get; private set; }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var act = filterContext.ActionDescriptor.ActionName;
            var cont = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            if ("Login".Equals(cont, StringComparison.CurrentCultureIgnoreCase) && "Index".Equals(act, StringComparison.CurrentCultureIgnoreCase))
                return;
            if (!User.Identity.IsAuthenticated || !User.IsInRole("User"))
            {
                filterContext.Result = RedirectToAction("Index", "Login", new { ReturnUrl = Request.IsAjaxRequest() ? "" : Request.RawUrl });
                return;
            }
            if ("Surrogate".Equals(cont, StringComparison.CurrentCultureIgnoreCase) && !User.IsInRole("Surrogate"))
            {
                string str = "<h2>您不是代理</h2><a href='javascript:history.go(-1)'>返回</a></p>";
                str += string.Format("<p>5秒之后将跳转到<a href='{0}'>首页</a></p><script>setTimeout(function(){{location.href='{0}'}},5000);</script>", Url.Action("Index", "Home"));
                filterContext.Result = Content(str);
                return;
            }

            var data = User.Identity.Name.Split('&').ToDictionary(p => p.Split(':')[0], p => p.Split(':')[1]);
            LoginUserID = (Guid)(Session["Login_Uid"] ?? new Guid(data["LoginID"]));
            Session["Login_Uid"] = LoginUserID;
            var manageLogin = User.IsInRole(AuthorityKey.Manage_User_Login.ToString());//是否是管理员从后台登录

            var them = data["Them"];
            if (string.IsNullOrEmpty(them))
                them = System.Configuration.ConfigurationManager.AppSettings["DefaultThem"];
            if (string.IsNullOrEmpty(them))
                them = Global.Thems.First();

            OnLineUsers = Global.OnLineUsers;
            if (!manageLogin)
                LoginUser = OnLineUsers[LoginUserID];
            if (!manageLogin && LoginUser != null && LoginUser.SessionID != Session.SessionID)
            {
                string str = string.Format("<script>alert('您的账号已在:{1}登录\\r\\n请尽快修改密码！');location.href='{0}';</script>", Url.Action("Index", "Login", new { ReturnUrl = Request.RawUrl }), LoginUser.LoginIP);
                filterContext.Result = Content(str);
                FormsAuthentication.SignOut();
                return;
            }

            if (LoginUser == null || LoginUser.IsLoad || LoginUser.AddTime.AddSeconds(3) < DateTime.Now)
            {
                var UM = new UserManage();
                var u = UM.Select(s => s.Select(p => new { p.ID, p.Commands, p.Account.Balance, p.Account.FreezeMoney, p.State, p.UserType, p.LoginName, p.Person.Email })
                    .FirstOrDefault(p => p.ID == LoginUserID));
                if (u == null)
                {
                    filterContext.Result = RedirectToAction("Index", "Login", new { ReturnUrl = Request.RawUrl });
                    return;
                }
                List<WinMoneyModel> ls = PlayTypeOptionManage.SelectIdFromPlayTypeOption(LoginUserID);
                if (LoginUser==null)
                {
                    if (ls[0].ID != int.Parse(data["WinModel"]))
                    {
                        data["WinModel"] = ls[0].ID.ToString();
                    }
                }
                LoginUser = new UserModel
                {
                    UserID = u.ID,
                    LoginName = u.LoginName,
                    Commands = u.Commands,
                    Balance = (double)u.Balance,
                    FreezeMoney = (double)u.FreezeMoney,
                    State = manageLogin ? UserState.Normal : (UserState)u.State,
                    UserType = (UserType)u.UserType,
                    Ratio = decimal.Parse(data["Ratio"]),
                    Email = u.Email,
                    WinModelID = int.Parse(data["WinModel"]),
                    LoginIP = Request.UserHostAddress,
                    SessionID = Session.SessionID,
                    Them = them,
                    AddTime = DateTime.Now,
                };
            }

            SetAuthTicket(LoginUser);
            if (!manageLogin)
                OnLineUsers[LoginUserID] = LoginUser;
            CheckState(filterContext);
            ViewData["Them"] = them;

            var _us = Global.OnLineUsers.Where(p => p.Value.SessionID == Session.SessionID && p.Value.UserID != LoginUserID).Select(p => p.Key).ToArray();

            foreach (var item in _us)
                Global.OnLineUsers.Remove(item);
        }

        protected void LoadUser()
        {

        }

        protected void CheckState(AuthorizationContext filterContext)
        {
            var act = filterContext.ActionDescriptor.ActionName;
            var cont = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            if (LoginUser.State == UserState.Locked || LoginUser.State == UserState.Locked_Manage)
            {
                string str = string.Format("<script>alert('您的账户已被{1}！');location.href='{0}';</script>", Url.Action("Index", "Login", new { ReturnUrl = Request.IsAjaxRequest() ? "" : Request.RawUrl }), LoginUser.State.GetName());
                filterContext.Result = Content(str);
                FormsAuthentication.SignOut();
                return;
            }
            var ratio = CacheManage.Ratio[LoginUser.Ratio];
            if (!Request.IsAjaxRequest())
            {
                if (!("Ratio".ToLower() == act.ToLower() && "Shared".ToLower() == cont.ToLower()) && ratio.State != (short)ConsumeRatioState.Normal)
                {
                    var ratio1 = CacheManage.Ratio.Values.FirstOrDefault(p => p.State == (short)ConsumeRatioState.Normal);
                    if (ratio1 != null)
                    {
                        var url = Url.Route(new { ratio1.ID, returnurl = Request.RawUrl });
                        ViewData["basemsg"] = Url.Action("Ratio", "Shared", url).Redirect(string.Format("{0}模式已经停用，现帮您切换到{1}模式。\\r\\n不更之处敬请谅解！！！", ratio.Name, ratio1.Name));
                    }
                }
                var winmodel = CacheManage.WinModel[LoginUser.WinModelID];
                if (!("WinModel".ToLower() == act.ToLower() && "Shared".ToLower() == cont.ToLower()) && winmodel.State != (short)WinMoneyModelState.Normal)
                {
                    var winmodel1 = CacheManage.WinModel.Values.FirstOrDefault(p => p.State == (short)WinMoneyModelState.Normal);
                    if (winmodel1 != null)
                    {
                        var url = Url.Route(new { winmodel1.ID, returnurl = Request.RawUrl });
                        ViewData["basemsg"] = Url.Action("WinModel", "Shared", url).Redirect(string.Format("{0}模式已经停用，现帮您切换到{1}模式。\\r\\n不更之处敬请谅解！！！", winmodel.Name, winmodel1.Name));
                    }
                }
            }
        }

        protected void SetAuthTicket(UserModel user)
        {
            HttpCookie authtick = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authtick == null)
                RedirectToAction("", "");

            FormsAuthenticationTicket tick = FormsAuthentication.Decrypt(authtick.Value);

            if (tick == null || tick.Expired)
                RedirectToAction("", "");

            var flag = User.IsInRole(AuthorityKey.Manage_User_Login.ToString());

            var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;
            if (aus != null)
            {
                var str = string.Format("LoginID:{0}&WinModel:{1}&Ratio:{2}&Roles:User{3}{4}&Them:{5}", user.UserID, user.WinModelID, (double)user.Ratio, flag ? "," + AuthorityKey.Manage_User_Login.ToString() : "", user.UserType == UserType.Surrogate ? ",Surrogate" : "", user.Them);
                tick = new FormsAuthenticationTicket(2, str, tick.IssueDate, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, tick.UserData);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                Response.Cookies.Add(cookie);
            }
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            string msg = "系统错误";
            if (filterContext.Exception is AppException)
                msg = filterContext.Exception.Message;
            ViewData["Error_Msg"] = msg;
            filterContext.Result = View("Error");
        }

        private object obj = new object();

        /// <summary>
        /// 日志记录对象
        /// </summary>
        protected static ILog Log = Code.Commen.Log.GetLog("BaseController");
    }
}
